<template>
  <view class="category-container">
    <!-- 全屏初始化加载动画 -->
    <view class="initial-loading-overlay" v-if="initialLoading">
      <view class="initial-loading-content">
        <view class="initial-loading-spinner"></view>
        <text class="initial-loading-text">正在加载...</text>
      </view>
    </view>

    <!-- 顶部搜索框 -->
    <view class="search-header">
      <uni-search-bar
        v-model="searchKeyword"
        placeholder="搜索商品"
        @confirm="onSearchConfirm"
        @input="onSearchInput"
        @clear="onSearchClear"
        clearButton="auto"
        radius="25"
      />
    </view>

    <!-- 主体内容 -->
    <view class="main-content">
      <!-- 左侧分类列表 -->
      <scroll-view
        class="category-sidebar"
        scroll-y
        :scroll-top="leftScrollTop"
      >
        <view
          v-for="(category, index) in categories"
          :key="category.id"
          :class="[
            'category-item',
            { active: selectedCategory === category.id },
          ]"
          @click="selectCategory(category)"
        >
          <text class="category-name">{{ category.name }}</text>
          <view
            v-if="selectedCategory === category.id"
            class="category-indicator"
          ></view>
        </view>
      </scroll-view>

      <!-- 右侧内容区域 -->
      <scroll-view class="content-area" scroll-y :scroll-top="rightScrollTop">
        <!-- 商品列表 -->
        <view class="products-section">
          <view class="section-title">
            <!-- <text class="title-text">{{ selectedCategoryName }}</text> -->
            <text class="product-count">
              共{{ filteredProducts.length }}件商品
            </text>
            <view class="title-right">
              <view class="filter-icon" @click="openBrandDrawer">
                <uni-icons type="list" color="#666"></uni-icons>
                <text class="filter-text">品牌</text>
              </view>
            </view>
          </view>
          <!-- 瀑布流布局 -->
          <view class="products-waterfall">
            <!-- 左列 -->
            <view class="waterfall-column">
              <view
                v-for="product in leftColumnProducts"
                :key="product.id"
                class="product-card"
                @click="goToProductDetail(product)"
              >
                <view class="product-image-wrapper">
                  <image
                    :src="product.mainImageUrl || '/static/default-product.png'"
                    mode="widthFix"
                    class="product-image"
                  />
                </view>
                <view class="product-info">
                  <text class="product-name">{{ product.productName }}</text>
                  <view class="product-price-row">
                    <text class="product-price">
                      ¥{{ product.sellingPrice / 100 }}
                    </text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 右列 -->
            <view class="waterfall-column">
              <view
                v-for="product in rightColumnProducts"
                :key="product.id"
                class="product-card"
                @click="goToProductDetail(product)"
              >
                <view class="product-image-wrapper">
                  <image
                    :src="product.mainImageUrl || '/static/default-product.png'"
                    mode="widthFix"
                    class="product-image"
                  />
                </view>
                <view class="product-info">
                  <text class="product-name">{{ product.productName }}</text>
                  <view class="product-price-row">
                    <text class="product-price"
                      >¥{{ product.sellingPrice / 100 }}</text
                    >
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载中 -->
        <view
          class="loading-container"
          v-if="loading && filteredProducts.length > 0"
        >
          <view class="loading-spinner"></view>
          <text class="loading-text">正在加载...</text>
        </view>

        <!-- 加载更多 -->
        <view
          class="load-more"
          v-if="hasMore && !loading && filteredProducts.length > 0"
        >
          <text class="load-text">上拉加载更多...</text>
        </view>

        <!-- 全部加载完成 -->
        <view
          class="no-more"
          v-if="!hasMore && !loading && filteredProducts.length > 0"
        >
          <text class="no-more-text">已全部加载完成</text>
        </view>

        <!-- 空状态 -->
        <view
          class="empty-state"
          v-if="filteredProducts.length === 0 && !initialLoading"
        >
          <image
            src="/static/icons/empty.png"
            mode="aspectFit"
            class="empty-icon"
          />
          <text class="empty-text">暂无商品</text>
        </view>
      </scroll-view>
    </view>

    <!-- 品牌筛选抽屉 -->
    <uni-drawer ref="brandDrawer" mode="right" :width="300">
      <view class="drawer-container">
        <view class="drawer-header">
          <text class="drawer-title">筛选</text>
          <view class="drawer-close" @click="closeBrandDrawer">
            <uni-icons type="closeempty" size="22" color="#666"></uni-icons>
          </view>
        </view>
        <scroll-view class="drawer-content" scroll-y>
          <view class="brand-grid">
            <view
              v-for="brand in brands"
              :key="brand.id"
              class="brand-item"
              :class="{ selected: selectedBrandId === brand.id }"
              @click="selectBrand(brand)"
            >
              <text class="brand-name">{{ brand.name }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-drawer>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onShow, onHide, onReachBottom } from '@dcloudio/uni-app';
import { getUserInfo } from '@/utils/auth';
import request from '@/utils/request';

// ==================== 数据类型定义 ====================
interface Category {
  id: string | number;
  name: string;
  icon?: string;
}

interface Brand {
  id: string | number;
  name: string;
  logo?: string;
}

// 商品接口类型定义（与首页保持一致）
interface ProductImage {
  ossId: string;
  fileName: string;
  originalName: string;
  fileSuffix: string;
  url: string;
  ext1: string;
  createTime: string;
  createBy: number;
  createByName: string;
  service: string;
  businessType: string;
  businessId: string;
}

interface Product {
  id: string;
  productName: string;
  sellingPrice: number;
  salesCommission: number | null;
  mainImage: ProductImage | null;
  mainImageUrl: string | null;
  mainImageId: string | null;
}

interface ProductListResponse {
  total: number;
  rows: Product[];
  code: number;
  msg: string;
}

// ==================== 页面状态 ====================
const initialLoading = ref(false);
const searchKeyword = ref('');
const selectedCategory = ref<string | number>('');
const selectedCategoryName = ref('');
const selectedBrandId = ref<string | number | null>(null);
const leftScrollTop = ref(0);
const rightScrollTop = ref(0);

// 抽屉引用
const brandDrawer = ref<any>(null);

// 搜索防抖定时器
const searchDebounceTimer = ref<any>(null);

// 分页状态
const pageNum = ref(1);
const pageSize = ref(20);
const total = ref(0);
const hasMore = ref(true);
const loading = ref(false);

// 数据状态
const categories = ref<Category[]>([]);
const brands = ref<Brand[]>([]);
const products = ref<Product[]>([]);

// ==================== API接口函数（待对接） ====================

/**
 * 获取商品分类列表
 * 接口路径: /dict-data/cates
 * 请求方式: GET
 * 请求参数: 无
 * 返回数据: { code: 200, data: [{ dictCode: string, dictValue: string }], msg: string }
 */
const getCategoryList = async () => {
  try {
    const response = await request({
      url: '/dict-data/cates',
      method: 'GET',
    });

    console.log('分类列表响应:', response);

    if (response.code === 200 && response.data) {
      // 将返回的数据格式转换为组件使用的格式
      categories.value = response.data.map((item: any) => ({
        // id: item.dictCode,
        id: item.dictValue,
        name: item.dictValue,
      }));

      // 默认选中第一个分类
      if (categories.value.length > 0) {
        selectedCategory.value = categories.value[0].id;
        selectedCategoryName.value = categories.value[0].name;
      }

      console.log('分类列表加载完成，数量:', categories.value.length);
    } else {
      uni.showToast({
        title: response.msg || '获取分类失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    uni.showToast({
      title: '获取分类失败',
      icon: 'none',
    });
  }
};

/**
 * 获取品牌列表（页面初始化时请求一次，固定不变）
 * 接口路径: /dict-data/bands
 * 请求方式: GET
 * 请求参数: 无
 * 返回数据: { code: 200, data: [{ dictCode: string, dictValue: string }], msg: string }
 */
const getBrandList = async () => {
  try {
    const response = await request({
      url: '/dict-data/bands',
      method: 'GET',
    });

    console.log('品牌列表响应:', response);

    if (response.code === 200 && response.data) {
      // 将返回的数据格式转换为组件使用的格式
      brands.value = response.data.map((item: any) => ({
        // id: item.dictCode,
        id: item.dictValue,
        name: item.dictValue,
      }));

      console.log('品牌列表加载完成，数量:', brands.value.length);
    } else {
      uni.showToast({
        title: response.msg || '获取品牌失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('获取品牌列表失败:', error);
    // 品牌加载失败不影响主流程，只记录日志
    console.log('品牌列表加载失败，继续使用空列表');
  }
};

/**
 * 获取商品列表（分页）
 * 接口路径: /product/list
 * 请求方式: GET
 * 请求参数:
 *   - productName?: string (可选，搜索关键词)
 *   - cateId?: string (可选，分类ID)
 *   - brandId?: string (可选，品牌ID)
 *   - pageNum: number (页码)
 *   - pageSize: number (每页数量)
 * 返回数据: { code: 200, total: number, rows: Product[], msg: string }
 */
const getProductList = async (isLoadMore: boolean = false) => {
  if (loading.value) return;

  try {
    loading.value = true;

    // 如果不是加载更多，重置页码
    if (!isLoadMore) {
      pageNum.value = 1;
      products.value = [];
    }

    // 构建请求参数
    const params: any = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    };

    // 添加可选参数
    if (searchKeyword.value) {
      params.productName = searchKeyword.value;
    }
    if (selectedCategory.value) {
      params.cateId = selectedCategory.value;
    }
    if (selectedBrandId.value) {
      params.brandId = selectedBrandId.value;
    }

    console.log('获取商品列表，参数:', params);

    const response = await request<ProductListResponse>({
      url: '/product/list',
      method: 'GET',
      data: params,
    });

    console.log('商品列表响应:', response);

    if (response.code === 200) {
      const newProducts = response.rows || [];

      if (isLoadMore) {
        // 加载更多时，追加到现有列表
        products.value = [...products.value, ...newProducts];
      } else {
        // 首次加载或搜索时，替换列表
        products.value = newProducts;
      }

      total.value = response.total || 0;

      // 判断是否还有更多数据
      hasMore.value = products.value.length < response.total;

      console.log('商品列表加载完成:', {
        currentPage: pageNum.value,
        currentCount: products.value.length,
        total: response.total,
        hasMore: hasMore.value,
      });
    } else {
      uni.showToast({
        title: response.msg || '获取商品失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    uni.showToast({
      title: '获取商品失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
  }
};

// ==================== 计算属性 ====================

// 瀑布流布局 - 左列商品
const leftColumnProducts = computed(() => {
  return products.value.filter((_, index) => index % 2 === 0);
});

// 瀑布流布局 - 右列商品
const rightColumnProducts = computed(() => {
  return products.value.filter((_, index) => index % 2 === 1);
});

// 用于显示商品总数
const filteredProducts = computed(() => {
  return products.value;
});

// ==================== 事件处理函数 ====================

/**
 * 选择分类
 */
const selectCategory = (category: Category) => {
  selectedCategory.value = category.id;
  selectedCategoryName.value = category.name;
  selectedBrandId.value = null; // 切换分类时清除品牌筛选
  rightScrollTop.value = 0; // 滚动到顶部

  // 重新加载商品列表
  getProductList(false);
};

/**
 * 搜索输入（带防抖）
 */
const onSearchInput = (value: any) => {
  searchKeyword.value = value;
  
  // 清除之前的防抖定时器
  if (searchDebounceTimer.value) {
    clearTimeout(searchDebounceTimer.value);
  }
  
  // 设置新的防抖定时器（500ms）
  searchDebounceTimer.value = setTimeout(() => {
    console.log('搜索:', searchKeyword.value);
    getProductList(false);
  }, 500);
};

/**
 * 搜索确认
 */
const onSearchConfirm = () => {
  console.log('搜索:', searchKeyword.value);
  // 重新加载商品列表
  getProductList(false);
};

/**
 * 清除搜索
 */
const onSearchClear = () => {
  searchKeyword.value = '';
  // 重新加载商品列表
  getProductList(false);
};

/**
 * 加载更多商品
 */
const loadMore = () => {
  if (loading.value || !hasMore.value) return;

  pageNum.value++;
  getProductList(true);
};

/**
 * 跳转到商品详情
 */
const goToProductDetail = (product: Product) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${product.id}`,
  });
};

/**
 * 打开品牌筛选抽屉
 */
const openBrandDrawer = () => {
  brandDrawer.value?.open();
};

/**
 * 关闭品牌筛选抽屉
 */
const closeBrandDrawer = () => {
  brandDrawer.value?.close();
};

/**
 * 选择品牌（单选，立即生效）
 */
const selectBrand = (brand: Brand) => {
  // 单选逻辑：如果点击已选中的品牌，则取消选择
  if (selectedBrandId.value === brand.id) {
    selectedBrandId.value = null;
  } else {
    selectedBrandId.value = brand.id;
  }

  // 立即刷新商品列表
  getProductList(false);
};

/**
 * 检查登录状态
 */
const checkLoginStatus = () => {
  const storedUserInfo = getUserInfo();
  if (!storedUserInfo) {
    console.log('分类页面：用户未登录，跳转到登录页');
    // uni.navigateTo({
    //   url: '/pages/user/login',
    // });
    return false;
  }
  return true;
};

/**
 * 初始化页面数据
 */
const initPageData = async () => {
  // 第一步：并行加载分类列表和品牌列表
  await Promise.all([
    getCategoryList(),
    getBrandList(), // 品牌列表只在初始化时加载一次
  ]);
  
  // 第二步：等分类加载完成并选中后，再加载商品列表
  // 这样确保商品列表请求时带上了分类ID
  if (selectedCategory.value) {
    await getProductList(false);
  }
};

// ==================== 生命周期 ====================

// 页面显示时
onShow(async () => {
  initialLoading.value = true;

  try {
    // 检查登录状态
    if (!checkLoginStatus()) {
      await new Promise((resolve) => setTimeout(resolve, 800));
      return;
    }

    // 初始化页面数据
    await initPageData();
  } catch (error) {
    console.error('页面初始化失败:', error);
  } finally {
    initialLoading.value = false;
  }
});

onMounted(() => {
  // 组件挂载时初始化
});

// 页面卸载时清理定时器
onUnmounted(() => {
  if (searchDebounceTimer.value) {
    clearTimeout(searchDebounceTimer.value);
    searchDebounceTimer.value = null;
  }
});

// 页面触底加载更多
onReachBottom(() => {
  loadMore();
});

// 页面隐藏/离开时清空品牌筛选（只重置状态，不做其他操作）
onHide(() => {
  selectedBrandId.value = null;
});
</script>

<style scoped>
.category-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 全屏加载动画 */
.initial-loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #ffffff;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.initial-loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.initial-loading-spinner {
  width: 70rpx;
  height: 70rpx;
  border: 6rpx solid rgba(255, 102, 0, 0.2);
  border-top: 6rpx solid #ff6600;
  border-radius: 50%;
  animation: spin 1.5s cubic-bezier(0.4, 0, 0.2, 1) infinite;
  margin-bottom: 40rpx;
}

.initial-loading-text {
  font-size: 32rpx;
  color: #ff6600;
  font-weight: 600;
  letter-spacing: 0.02em;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 搜索框样式 */
.search-header {
  background: #fff;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.filter-icon {
  flex-shrink: 0;
  display: flex;
  /* flex-direction: column; */
  align-items: center;
  justify-content: center;
  gap: 4rpx;
  padding: 8rpx;
  transition: all 0.3s ease;
}

.filter-icon:active {
  transform: scale(0.9);
}

.filter-text {
  font-size: 26rpx;
  color: #666;
}

/* 主体内容 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧分类栏 */
.category-sidebar {
  width: 180rpx;
  background: #fff;
  border-right: 1rpx solid #e5e5e5;
}

.category-item {
  position: relative;
  padding: 32rpx 20rpx;
  text-align: center;
  border-bottom: 1rpx solid #f5f5f5;
  transition: all 0.3s ease;
}

.category-item.active {
  background: #f5f7fa;
}

.category-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 400;
}

.category-item.active .category-name {
  color: #007aff;
  font-weight: 600;
}

.category-indicator {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 40rpx;
  background: #007aff;
  border-radius: 0 6rpx 6rpx 0;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  background: #f5f7fa;
}

/* 商品列表 */
.products-section {
  padding: 12rpx;
}

.section-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 12rpx 16rpx;
  background: #fff;
}

.title-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
}

.title-right {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.product-count {
  font-size: 24rpx;
  color: #999;
}

/* 瀑布流布局 */
.products-waterfall {
  display: flex;
  gap: 12rpx;
  align-items: flex-start;
}

.waterfall-column {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-card {
  width: 100%;
  background: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  margin-bottom: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  border: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.product-card:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
}

.product-image-wrapper {
  position: relative;
  overflow: hidden;
}

.product-image {
  width: 100%;
  display: block;
  border-radius: 8rpx 8rpx 0 0;
}

.product-info {
  padding: 12rpx;
}

.product-name {
  font-size: 24rpx;
  color: #333;
  font-weight: 400;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
  margin-bottom: 8rpx;
}

.product-price-row {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  margin-bottom: 6rpx;
}

.product-price {
  font-size: 28rpx;
  color: #ff6600;
  font-weight: 600;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.loading-spinner {
  width: 48rpx;
  height: 48rpx;
  border: 4rpx solid rgba(255, 102, 0, 0.2);
  border-top: 4rpx solid #ff6600;
  border-radius: 50%;
  animation: spin 1.2s cubic-bezier(0.4, 0, 0.2, 1) infinite;
  margin-bottom: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #888;
  font-weight: 500;
}

.load-more,
.no-more {
  text-align: center;
  padding: 40rpx 0;
}

.load-text,
.no-more-text {
  font-size: 28rpx;
  color: #888;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 品牌筛选抽屉 */
.drawer-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.drawer-header {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.drawer-title {
  font-size: 30rpx;
  color: #333;
  font-weight: 600;
}

.drawer-close {
  padding: 8rpx;
}

.drawer-content {
  flex: 1;
  height: 0;
  padding: 24rpx;
}

.brand-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.brand-item {
  width: calc((100% - 160rpx) / 3);
  padding: 12rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  text-align: center;
  transition: all 0.3s ease;
  line-height: 40rpx;
}

.brand-item:active {
  transform: scale(0.95);
}

.brand-item.selected {
  background: #ff6600;
  border-color: #ff6600;
}

.brand-name {
  font-size: 24rpx;
  color: #333;
}

.brand-item.selected .brand-name {
  color: #fff;
  font-weight: 500;
}
</style>
